import React, { useState } from 'react';
import ProTable from '@ant-design/pro-table';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import FormRender, { useForm } from 'form-render';
// 搜索 表头
import columnsData, { columnsDataType, usrColumns, DataType } from './data';
// 模拟的数据
import tableData from '../../mock/tableData';
import { message, Modal, Row, Col, Table, Tag } from 'antd';
import {
  getAllTask,
  completeTask,
  completeTaskWithForm,
} from '../../services/processTask';
import {
  getTasksByUser,
  delegateTask,
  transfer,
  resolveTask,
  complete,
} from '../../services/todoTask';
import {
  startProcessInstanceWithForm,
  getProcessDefinitionTaskFormData,
} from '../../services/processFormRepository';
import SearchTree from '../../components/SearchTree';
import { getOrgTree, getUser } from '../../services/upmsServices';
import { flowableToFormEngine } from '../../utils/formSchemaTransform';
import { ModelView } from 'bsin-workflow-ui';
import TaskHandle from '../TaskHandle';

const TodoTask = () => {
  // table 绑定
  const tableRef = React.useRef<ActionType>();
  const [id, setID] = useState('');
  const [delegateModel, setDelegateModel] = useState(false);
  // 审批人key
  const [approversKey, setApproversKey] = React.useState<React.Key[]>([]);
  // 表格数据
  const [tableData, setTableData] = React.useState([]);
  // 树数据
  const [orgTree, setOrgTree] = React.useState([]);
  // 组织id
  const [orgId, setOrgId] = React.useState<string>('');
  // 委派或转办
  const [type, setType] = React.useState('');
  const [handleModel, setHandleModel] = useState(false);
  const [formSchema, setFormSchema] = useState({});
  const [taskId, setTaskId] = useState('');
  const [handleModelView, setHandleModelView] = useState(false);
  const [processInstanceId, setProcessInstanceId] = useState('');
  const [processDefinitionId, setProcessDefinitionId] = useState('');
  const [itemInfo, setItemInfo] = useState({});
  const [processingModel, setProcessingModel] = useState(false);

  // 表头数据
  const columns: ProColumns<columnsDataType>[] = columnsData;

  // 操作 确认
  const confirm = async (processInstanceId: string, isSuspended: boolean) => {
    tableRef.current?.reload();
  };

  // 操作 取消
  const onCancel = () => {};

  // 获取机构树
  const getOrgList = async () => {
    let res = await getOrgTree({});
    if (res.code !== '000000') {
      message.error('获取机构信息失败');
      return;
    }
    setOrgTree(setTree(res.data));
  };

  // 打造机构树
  const setTree = (arr: any) => {
    let tree = arr.map((item: any) => {
      let obj = {
        title: item.orgName,
        key: item.orgId,
        children: [],
      };
      if (item.children.length !== 0) {
        obj.children = setTree(item.children);
      }
      return obj;
    });
    return tree;
  };

  // 任务委派/转办确认
  const handleOk = async () => {
    if (type == '委派') {
      let res = await delegateTask({ taskId: id, assignee: approversKey[0] });
      console.log(res);
      if (res.code == '000000') {
        message.success('委派任务成功');
      } else {
        message.error('委派任务失败');
      }
    } else if (type == '转办') {
      let res = await transfer({ taskId: id, assignee: approversKey[0] });
      console.log(res);
      if (res.code == '000000') {
        message.success('转办任务成功');
      } else {
        message.error('转办任务失败');
      }
    }
    tableRef.current?.reload();
    setDelegateModel(false);
    setApproversKey([]);
    setOrgId('');
  };

  // 任务委派取消
  const handleCancel = () => {
    setDelegateModel(false);
  };

  // 表格勾选函数
  const onSelectChange = (
    selectedRowKeys: React.Key[],
    selectedRows: DataType[],
  ) => {
    setApproversKey(selectedRowKeys);
  };

  // 表格设置
  const rowSelection = {
    selectedRowKeys: approversKey,
    onChange: onSelectChange,
  };

  // 获取表格数据
  const getTableData = async (orgId: string) => {
    setOrgId(orgId);
    let res = await getUser({ orgId });
    if (res.code !== '000000') {
      message.error('获取审批人表格失败');
      return;
    }
    setTableData(res.data);
  };

  // 办理
  const transact = async (record: any) => {
    setTaskId(record.id);
    // 查询判断是否有表单需要提交
    let res = await getProcessDefinitionTaskFormData({
      taskId: record.id,
    });
    if (res.data == '' || record.delegation == 'RESOLVED') {
      // 没有则直接提交
      // 完成任务
      let completeTaskRes = await complete({
        taskId: record.id,
      });
      console.log(completeTaskRes);
      tableRef.current?.reload();
      if (completeTaskRes.code == '000000') {
        return message.success('处理成功');
      }
      return message.error('处理失败');
    } else if (res.data != '') {
      // 有表单数据
      // 有表单则渲染表单
      console.log('通过');
      let obj = flowableToFormEngine(res.data);
      console.log(JSON.stringify(obj));
      setFormSchema(obj);
      setHandleModel(true);
    }
  };

  // 操作行数据 自定义操作行
  const actionRender: any = (text: any, record: any, index: number) => (
    <ul className="ant-list-item-action" style={{ margin: 0 }}>
      {!record.delegation ? (
        <li>
          <a
            onClick={() => {
              setItemInfo(record);
              setProcessingModel(true);
              // transact(record);
            }}
          >
            办理
          </a>
          <em className="ant-list-item-action-split"></em>
        </li>
      ) : record.delegation == 'PENDING' ? (
        <li>
          <a
            onClick={() => {
              setItemInfo(record);
              setProcessingModel(true);
            }}
          >
            解决
          </a>
          <em className="ant-list-item-action-split"></em>
        </li>
      ) : record.delegation == 'RESOLVED' ? (
        <li>
          <a
            onClick={() => {
              transact(record);
            }}
          >
            完成
          </a>
        </li>
      ) : null}
      {record.delegation == 'RESOLVED' ? null : (
        <>
          {/* <li>
            <a
              onClick={() => {
                getOrgList();
                setID(record.id);
                setDelegateModel(true);
                setType('委派');
              }}
            >
              委派
            </a>
            <em className="ant-list-item-action-split"></em>
          </li>
          <li>
            <a
              onClick={() => {
                getOrgList();
                setID(record.id);
                setDelegateModel(true);
                setType('转办');
              }}
            >
              转办
            </a>
          </li> */}
          <li>
            <a
              onClick={() => {
                setHandleModelView(true);
                setProcessInstanceId(record.processInstanceId);
                setProcessDefinitionId(record.processDefinitionId);
              }}
            >
              流程预览
            </a>
          </li>
        </>
      )}
    </ul>
  );

  // 自定义数据的表格头部数据
  columns.forEach((item: any) => {
    item.dataIndex === 'action' ? (item.render = actionRender) : undefined;
  });

  const form = useForm();

  // 发起表单提交确认
  const handleFormOk = async () => {
    console.log(form.getValues());
    console.log(form.formData);
    let res = await complete({
      variables: form.formData,
      taskId,
    });
    setHandleModel(false);
    tableRef.current?.reload();
    if (res.code != '000000') {
      return message.error('处理失败');
    }
    message.success('处理成功');
  };

  // 发起表单提交取消
  const handleFormCancel = () => {
    setHandleModel(false);
  };

  const onFinish = (formData: any, errors: any) => {
    console.log('formData:', formData, 'errors', errors);
  };

  // 处理弹框确定
  const processingModelOk = () => {
    setProcessingModel(false);
  };

  // 处理弹框取消
  const processingModelCancel = () => {
    setProcessingModel(false);
    tableRef.current?.reload();
  };

  return (
    <div>
      {/* Pro表格 */}
      <ProTable<columnsDataType>
        headerTitle="我的待办"
        scroll={{ x: 1000 }}
        actionRef={tableRef}
        bordered
        // 表头
        columns={columns}
        // 请求获取的数据
        request={async (params) => {
          let res = await getTasksByUser({
            ...params,
            pageNum: params.current,
          });
          console.log(res);
          if (res.code !== '000000') {
            message.error('获取流程任务表格信息失败');
          }
          const result = {
            data: res.data,
            total: res.pagination?.totalSize,
          };
          return result;
        }}
        // defaultData={tableData}
        rowKey="id"
        // 本地存储表格列的显示数据
        columnsState={{
          persistenceKey: 'todoTask',
          persistenceType: 'localStorage',
        }}
        // 搜索框配置
        search={{
          labelWidth: 'auto',
        }}
        // 搜索表单的配置
        form={{
          ignoreRules: false,
        }}
        pagination={{
          pageSize: 5,
        }}
        dateFormatter="string"
      />
      <Modal
        title={`选择${type}人`}
        open={delegateModel}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Row gutter={16} style={{ marginTop: 10 }}>
          <Col span={6}>
            <SearchTree
              // 渲染数据
              checkedId={orgId}
              treeData={orgTree}
              changeKey={getTableData}
            />
          </Col>
          <Col span={18}>
            <Table
              rowSelection={{
                type: 'radio',
                ...rowSelection,
              }}
              columns={usrColumns}
              dataSource={tableData}
              rowKey="userId"
            />
          </Col>
        </Row>
      </Modal>
      <Modal
        title="办理"
        open={handleModel}
        onOk={handleFormOk}
        onCancel={handleFormCancel}
      >
        <div style={{ margin: '0 20px 0 0' }}>
          <FormRender form={form} schema={formSchema} onFinish={onFinish} />
        </div>
      </Modal>
      <Modal
        title="流程预览"
        open={handleModelView}
        onCancel={() => setHandleModelView(false)}
        onOk={() => setHandleModelView(false)}
        destroyOnClose
        width={1000}
      >
        <ModelView
          processInstanceId={processInstanceId}
          processDefinitionId={processDefinitionId}
        />
      </Modal>
      <Modal
        title="任务办理"
        width={1000}
        footer={null}
        open={processingModel}
        // onOk={processingModelOk}
        onCancel={processingModelCancel}
        destroyOnClose
      >
        <TaskHandle
          itemInfo={itemInfo}
          processingModelCancel={processingModelCancel}
        ></TaskHandle>
      </Modal>
    </div>
  );
};

export default TodoTask;
